import { create } from 'zustand'
import { persist } from 'zustand/middleware'

interface AuthState {
  token: string | null
  user: { id: string; email: string; username: string; role: string } | null
  setLogin: (token: string, user: AuthState['user']) => void
  logout: () => void
  isAuthenticated: () => boolean
}

const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      token: null,
      user: null,
      
      setLogin: (token, user) => set({ token, user }),
      
      logout: () => {
        set({ token: null, user: null })
        // 不在这里处理跳转，让调用方自己处理
      },
      
      isAuthenticated: () => !!get().token
    }),
    {
      name: 'auth-storage',
    }
  )
)

// 只保持storage监听
if (typeof window !== 'undefined') {
  window.addEventListener('storage', (event) => {
    if (event.key === 'auth-storage' && !event.newValue) {
      useAuthStore.getState().logout()
    }
  })
}

export default useAuthStore
